import fg from "fast-glob";
import fs from "fs-extra";
import path from "path";
import { SVNClient } from "@taiyosen/easy-svn"
import moment from "moment";
import { toolchain } from "../toolchain.js";

export class LegacyFinder {
    public async lookUp(): Promise<void> {
        if (!toolchain.opts.input) {
            throw 'use -i to specify the base date';
        }
        const baseDate = moment(toolchain.opts.input);
        
        const svn = new SVNClient();
        svn.setConfig({ silent: true });

        const legacies: string[] = [];
        const reserves: string[] = [];
        const legacyOut: string[] = [];
        const reservedOut: string[] = [];

        const dir = path.join(toolchain.opts.projectRoot, 'Assets/AssetSources/ui/atlas/specialize/new');
        const moveTo = 'Assets/AssetSources/ui/atlas/specialize/new2';
        const files = await fg(['**/*.png', '**/*.jpg', '**/*.tga'], { cwd: dir });

        for (const f of files) {
            const file = path.join(dir, f);
            const info = await svn.info([file], { revision: 'BASE' });
            const authorMch = info.match(/Last Changed Author: (\S+)/);
            const dateMch = info.match(/Last Changed Date: (\S+)/);
            if (authorMch != null && dateMch != null) {
                const resolvedFile = path.relative(toolchain.opts.projectRoot, file).replaceAll('\\', '/');
                const author = authorMch[1];
                const date = dateMch[1];
                if (moment(date).diff(baseDate, 'd') < 0) {
                    legacies.push(author + ', ' + date + ', ' + file);
                    legacyOut.push(resolvedFile, resolvedFile + '.meta');
                } else {
                    reserves.push(author + ', ' + date + ', ' + file);
                    reservedOut.push('svn mv ' + resolvedFile + ' ' + moveTo, 'svn mv ' + resolvedFile + '.meta ' + moveTo);
                }
            }
        }

        console.log(`----------------legacy: ${legacies.length}----------------`);
        for (const l of legacies) {
            console.log(l);
        }

        console.log(`----------------reserved: ${reserves.length}----------------`);
        for (const r of reserves) {
            console.log(r);
        }

        await fs.writeFile(toolchain.opts.output?.replace('$', 'legacy') || 'legacy.txt', legacyOut.join('\n'));
        await fs.writeFile(toolchain.opts.output?.replace('$', 'reserved') || 'reserved.txt', reservedOut.join('\n') + '\n');
    }
}
